<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="授权用户列表"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      rowKey="userId"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button
          type="primary"
          plain
          :icon="CirclePlus"
          @click="addAuthUserDrawer()"
          v-permission="'systemRoleAuthUserAddBatch'"
          >添加用户</el-button
        >
        <el-button
          type="danger"
          plain
          :icon="CircleClose"
          @click="cancelAuthUserBatch(scope.selectedListIds)"
          :disabled="!scope.isSelected"
          v-permission="'systemRoleAuthUserDeleteBatch'"
          >批量取消授权</el-button
        >
        <el-button type="warning" plain :icon="Close" @click="closePage()">关闭</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button
          type="primary"
          link
          :icon="CircleClose"
          @click="cancelAuthUser(scope.row)"
          v-if="!scope.row.isSuperAdmin"
          v-permission="'systemRoleAuthUserDeleteBatch'"
          >取消授权</el-button
        >
      </template>
    </ProTable>
    <RoleAllowAuthUserDialog ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="systemRoleAuthUser">
import { ref, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { CirclePlus, CircleClose, Close } from "@element-plus/icons-vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { useTabsStore } from "@/stores/modules/tabs";
import ProTable from "@/components/ProTable/index.vue";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { getRoleAuthUserApi, deleteRoleAuthUserBatchApi } from "@/api/modules/role";
import { Role } from "@/api/interface/systemRole";
import RoleAllowAuthUserDialog from "@/views/system/components/RoleAllowAuthUserDialog.vue";

const route = useRoute();
const router = useRouter();
const tabStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

const roleId: number = parseInt(router.currentRoute.value.query.roleId as string);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  roleId: roleId
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.rows,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  return getRoleAuthUserApi(params);
};

// 表格配置项
const columns: ColumnProps<Role.RoleAuthUserRes>[] = [
  { type: "selection", fixed: "left" },
  {
    prop: "userId",
    label: "用户编号"
  },
  {
    prop: "account",
    label: "用户账号",
    search: { el: "input" }
  },

  {
    prop: "nickName",
    label: "用户昵称"
  },
  {
    prop: "email",
    label: "用户邮箱"
  },
  {
    prop: "phoneNumber",
    label: "手机号码",
    search: { el: "input" }
  },
  {
    prop: "status",
    label: "状态",
    render: scope => {
      return (
        <>
          <el-tag type={scope.row.status == 1 ? "success" : "danger"}>{scope.row.status == 1 ? "启用" : "禁用"}</el-tag>
        </>
      );
    }
  },
  {
    prop: "createTime",
    label: "创建时间",
    search: {
      el: "date-picker",
      props: { type: "daterange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
    }
  },
  { prop: "operation", label: "操作", fixed: "right" }
];

// 取消用户授权
const cancelAuthUser = (authUser: Role.RoleAuthUserRes) => {
  if (authUser.isSuperAdmin) {
    ElMessage({
      type: "error",
      message: `超级管理员不允许操作!`
    });
  } else {
    const userIds: string[] = [String(authUser.userId)];
    cancelAuthUserBatch(userIds);
  }
};

// 批量取消用户授权
const cancelAuthUserBatch = (userIds: string[] | undefined) => {
  if (undefined == userIds) {
    ElMessage({
      type: "error",
      message: `请选择用户!`
    });
    return;
  }
  const userIdNews: number[] = userIds.map(Number);
  const deleteRoleAuthUserRe: Role.RoleAuthUserDeleteBatchReq = {
    roleId: roleId,
    userIds: userIdNews
  };
  deleteRoleAuthUserBatchApi(deleteRoleAuthUserRe).then(res => {
    if (res.isSuccessful) {
      ElMessage({
        type: "success",
        message: `授权用户删除成功!`
      });
    } else {
      ElMessage({
        type: "error",
        message: `${res.message}`
      });
    }

    proTable.value?.getTableList();
  });
};

// 关闭页面
const closePage = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  keepAliveStore.removeKeepAliveName(route.name as string);
};

const dialogRef = ref<InstanceType<typeof RoleAllowAuthUserDialog> | null>(null);
const addAuthUserDrawer = () => {
  const params = {
    roleId: roleId,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};
</script>
